package com.xuecheng.framework.exception;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.common.collect.ImmutableMap;
import com.xuecheng.framework.model.response.CommonCode;
import com.xuecheng.framework.model.response.ResponseResult;
import com.xuecheng.framework.model.response.ResultCode;

/*
 * 统一异常捕获类
 */
@ControllerAdvice//控制器增强
public class ExceptionCatch {
    
    //获取日志对象
    private static final Logger LOGGER = LoggerFactory.getLogger(ExceptionCatch.class);
    
    //定义map，配置异常类型所对应的错误代码
    private static ImmutableMap<Class<? extends Throwable>, ResultCode> EXCEPTIONS;
    
    //定义map的builder对象，用于构建ImmutableMap
    protected static ImmutableMap.Builder<Class<? extends Throwable>, ResultCode> builder = ImmutableMap.builder();
    
    //捕获CustomException自定义类型异常
    @ExceptionHandler(CustomException.class)
    @ResponseBody//转成json格式数据
    public ResponseResult customException(CustomException customException) {
        //记录日志
        LOGGER.error("catch exception:{}",customException.getMessage());
        ResultCode resultCode = customException.getResultCode();//获取错误码
        return new ResponseResult(resultCode);
    }
    
    //捕获Exception类型异常
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public ResponseResult exception(Exception exception) {
        LOGGER.error("catch exception:{}",exception.getMessage());
        if(EXCEPTIONS == null) {//为空时进行构建
            EXCEPTIONS = builder.build();
        }
        //从EXCEPTIONS中获取错误代码
        ResultCode resultCode = EXCEPTIONS.get(exception.getClass());
        //找到则将错误代码响应给客户端
        if(resultCode!=null) {
            return new ResponseResult(resultCode);
        }else {//找不到返回99999错误
            return new ResponseResult(CommonCode.SERVER_ERROR); 
        }
    }
    
    static {
        //定义异常类型所对应的错误代码
        builder.put(HttpMessageNotReadableException.class,CommonCode.INVALID_PARAM);
    }

}
